package com.seagox.desk.auth.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.seagox.desk.common.ResultCode;
import com.seagox.desk.common.ResultData;
import com.seagox.desk.util.UploadUtils;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
	
	@Value("${oss.endpoint}")
    private String endpoint;
	
	@Value("${oss.url}")
    private String ossUrl;
	
	@Autowired
    private UploadUtils uploadUtils;

	/**
	 * 文件上传
	 */
	@PostMapping("/putObject/{bucketName}")
	public ResultData putObject(@RequestParam("file") MultipartFile file, @PathVariable String bucketName, Long companyId) {
		String address = uploadUtils.putObject(bucketName, file);
		if(StringUtils.isEmpty(address)) {
			return ResultData.warn(ResultCode.OTHER_ERROR, "文件服务器配置有误");
		} else {
			return ResultData.success(address);
		}
	}

	/**
	 * 下载文件
	 *
	 * @param response
	 */
	@PostMapping("/download")
	public void download(HttpServletResponse response, String url, String fileName) {
        url = url.replace(ossUrl, endpoint);
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("GBK"), "ISO-8859-1"));
			response.setContentType("application/octet-stream;charset=UTF-8");
			inputStream = new URL(URLEncoder.encode(url, "UTF-8")).openStream();
			outputStream = response.getOutputStream();
			IOUtils.copy(inputStream, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}